"""
Case Type   : datakit并行安装数据库
Case Name   : 创建并行安装任务，点击所属AZ下拉框，显示所有已有的AZ
Create At   : 2025/06/09
Owner       : @ningyali
Description :
    1.导入备服务器
    2.备节点添加用户
    3.获取备节点安装用户列表
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import subprocess
import unittest

import requests
from testcase.utils.Common import Common
from testcase.utils.CommonDatakit import CommonDatakit
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.datakit_api.BaseOpsApi import BaseOpsApi
from testcase.utils.datakit_api.CommonApi import CommonApi
from yat.test import Node
from yat.test import macro


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.az_id_lists = list()

        text = '----prestep1:获取token expect:执行成功----'
        self.log.info(text)
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotIn("error", self.token.lower(), f'执行失败:{text}')

        self.base_ops_api = BaseOpsApi(self.token)
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + self.token}

    def test_batch_installation(self):
        text = '----step1:新增可用区 expect:成功----'
        self.log.info(text)
        api = f'/az'
        for i in range(1, 11):
            data = {"azId": "", "name": f"az_batch0022_{i}",
                    "address": f"location_batch0022_{i}", "remark": "",
                    "privateIp": "", "publicIp": "", "password": ""}
            response = requests.post(
                url=self.base_ops_api.ip + api, headers=self.headers,
                json=data, verify=False)
            self.log.info(f'response.text:{response.text}')
            self.assertEqual(200, response.json()['code'], f'执行成功:{text}')

        text = '----step2:获取az列表 expect:成功----'
        self.log.info(text)
        api = f'/plugins/base-ops/clusterTask/list/az'
        response = requests.get(
            url=self.base_ops_api.ip + api, headers=self.headers, verify=False)
        self.log.info(f'response.text:{response.text}')
        for item in response.json()["data"]:
            self.az_id_lists.append(item.get('azId', ''))
        self.assertGreaterEqual(len(self.az_id_lists), 10, f'执行成功:{text}')

    def tearDown(self):
        text = '----step3:删除az expect:成功----'
        self.log.info(text)
        for azid in self.az_id_lists:
            api = f'/az/{azid}'
            response = requests.delete(
                url=self.base_ops_api.ip + api, headers=self.headers,
                verify=False)
            self.log.info(f'response.text:{response.text}')
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
